using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Navigation;
using Lib.Approval;
using Lib.Helper;
using Lib.Mail;
using MSIACCSL2.ApplicationStateServices;
using MSIACCSL2.Command;
using MSIACCSL2.CustomerServices;
using MSIACCSL2.InventoryServices;
using MSIACCSL2.ItemServices;
using MSIACCSL2.PalletServices;
using MSIACCSL2.PreSalesOrderServices;
using MSIACCSL2.SalesInvoiceServices;
using MSIACCSL2.SalesOrderServices;
using MSIACCSL2.SubGroupServices;
using MSIACCSL2.Views.PreSalesOrder;
using MSIACCSL2.WarehouseServices;
using WcfService1.DTO;
using DeleteDetailCompletedEventArgs = MSIACCSL2.PreSalesOrderServices.DeleteDetailCompletedEventArgs;
using GetListByCriteriaCompletedEventArgs = MSIACCSL2.PreSalesOrderServices.GetListByCriteriaCompletedEventArgs;
using GetListCompletedEventArgs = MSIACCSL2.PreSalesOrderServices.GetListCompletedEventArgs;
using SaveCompletedEventArgs = MSIACCSL2.PreSalesOrderServices.SaveCompletedEventArgs;

namespace MSIACCSL2.ViewModels
{
    public class PreSalesOrderViewModel : ViewModelBase
    {
        #region Delegates

        public delegate void Completed(Object param);

        #endregion

        public static Mode mode;
        private static Search frmSearch;
        private readonly AplicationStateServicesClient ApplicationService;
        private readonly CustomerServicesClient CustomerClient;
        private readonly ItemServicesClient ItemClient;
        private readonly PalletServicesClient PalletClient;
        private readonly SalesInvoiceServicesClient SalesInvoiceClient;
        private readonly SubGroupServiceClient SubgroupClient;
        private readonly WarehouseServicesClient WarehouseClient;
       

        private readonly ValidationHandler validationHandler;
        private int CurrentPage;
        private InventoryServiceClient InventoryClient;
        private bool IsUsed;
        public  static Completed OnSearchCompleted;
        private string OrderType;
        private ObservableCollection<int> Pages;
        private string PropertySort;
        private string TextCustomer;
        private PreSalesOrderDetailDTO _CurrentPreSalesOrderDetail;
        private ObservableCollection<CustomerDTO> _CustomerSearchs;
        private Visibility _CustomerVisibility;
        private ObservableCollection<CustomerDTO> _Customers;
        private string _Expression;
        private ObservableCollection<InventoryDTO> _Inventories;
        private bool _IsBusy;
        private bool _IsEnabled;
        private NavigationService _NavigationService;
        private PreSalesOrderDTO _PreSalesOrder;
        private PagedCollectionView _PreSalesOrders;
        private List<string> _errors;
        private InventoryDTO _inventory;
        private ObservableCollection<ItemDTO> _items;
        private Visibility _messageVisibility;
        private PagedCollectionView _pageSources;
        private ObservableCollection<PalletDTO> _pallets;
        private string _serialNumber;
        private ObservableCollection<SubGroupDTO> _subgroups;
        private ObservableCollection<WarehouseDTO> _warehouses;
        private PreSalesOrderServicesClient client;
        private int x;
        private Dictionary<string, object> criteria;
        private string expression;
        private ObservableCollection<SalesOrderDTO> _SalesOrders;
        private SalesOrderServicesClient SalesOrderClient;

        public PreSalesOrderViewModel()
        {
            IsEnabled = true;
            if (!DesignerProperties.IsInDesignTool)
            {
                client = new PreSalesOrderServicesClient();
                CustomerClient = new CustomerServicesClient();
                ItemClient = new ItemServicesClient();
                SubgroupClient = new SubGroupServiceClient();
                WarehouseClient = new WarehouseServicesClient();
                PalletClient = new PalletServicesClient();
                ApplicationService = new AplicationStateServicesClient();


                OnPageChanged = new DelegateCommand(PageIndexChanged, CanPageIndexChanged);
                Save = new DelegateCommand(SavePreSalesOrder, CanSave);
                New = new DelegateCommand(NewPreSalesOrder, CanNew);
                Unload = new DelegateCommand(Release, CanUnload);
                SearchCommand = new DelegateCommand(SearchPreSalesOrder, CanSearch);
                SearchResultCommand = new DelegateCommand(SearchResult, CanSearchResult);
                CancelCommand = new DelegateCommand(Cancel, CanCancelCommand);
                validationHandler = new ValidationHandler();
                MessageVisibility = Visibility.Collapsed;
                GetCustomerCommand = new DelegateCommand(GetCustomer, CanGetCustomer);
                CustomerVisibility = Visibility.Collapsed;
                InventoryClient = new InventoryServiceClient();


                if (mode == Mode.Edit)
                {
                    PrepareEdit();
                }
                else if (mode == Mode.Search)
                {
                    PreSalesOrder = new PreSalesOrderDTO();
                    PreSalesOrder.SRDate = null;
                }
                else if (mode == Mode.Add)
                {
                    //GetLastNoPreSalesOrder();
                    PreSalesOrder = new PreSalesOrderDTO();
                    PreSalesOrder.PreSalesOrderDetails = new ObservableCollection<PreSalesOrderDetailDTO>();
                    GetWarehouseList();
                    //CekTransaksi();
                }
                else
                {
                    GetList(1, null);
                }
            }
        }


        public PagedCollectionView PreSalesOrders
        {
            get { return _PreSalesOrders; }

            private set
            {
                if (PreSalesOrders == value) return;
                _PreSalesOrders = value;
                int i = (CurrentPage*30);
                foreach (object PreSalesOrder in PreSalesOrders)
                {
                    i += 1;

                    ((PreSalesOrderDTO) PreSalesOrder).No = i;
                }
                FirePropertyChanged("PreSalesOrders");
                PreSalesOrders.CollectionChanged += PreSalesOrder_CollectionChanged;
            }
        }

        public PagedCollectionView PageSources
        {
            get { return _pageSources; }
            private set
            {
                if (PageSources == value) return;
                _pageSources = value;
                FirePropertyChanged("PageSources");
            }
        }


        public ObservableCollection<CustomerDTO> Customers
        {
            get { return _Customers; }
            private set
            {
                if (Customers == value) return;
                _Customers = value;
                FirePropertyChanged("Customers");
            }
        }

        public ObservableCollection<CustomerDTO> CustomerSearch
        {
            get { return _CustomerSearchs; }
            private set
            {
                if (CustomerSearch == value) return;
                _CustomerSearchs = value;
                FirePropertyChanged("CustomerSearch");
            }
        }


        public ObservableCollection<InventoryDTO> InventorySearchs
        {
            get { return _Inventories; }
            private set
            {
                if (InventorySearchs == value) return;
                _Inventories = value;
                FirePropertyChanged("InventorySearchs");
            }
        }

        public ObservableCollection<SalesOrderDTO> SalesOrders
        {
            get { return _SalesOrders; }
            private set
            {
                if (SalesOrders == value) return;
                _SalesOrders = value;
                FirePropertyChanged("SalesOrders");
            }
        }

        public ObservableCollection<ItemDTO> Items
        {
            get { return _items; }
            private set
            {
                if (Items == value) return;
                _items = value;
                FirePropertyChanged("Items");
            }
        }

        public ObservableCollection<WarehouseDTO> Warehouses
        {
            get { return _warehouses; }
            private set
            {
                if (Warehouses == value) return;
                _warehouses = value;
                FirePropertyChanged("Warehouses");
            }
        }

        public ObservableCollection<PalletDTO> Pallets
        {
            get { return _pallets; }
            private set
            {
                if (Pallets == value) return;
                _pallets = value;
                FirePropertyChanged("Pallets");
            }
        }

        public ObservableCollection<SubGroupDTO> Subgroups
        {
            get { return _subgroups; }
            private set
            {
                if (Subgroups == value) return;
                _subgroups = value;
                FirePropertyChanged("Subgroups");
            }
        }

        public String SerialNumber
        {
            get { return _serialNumber; }
            set
            {
                if (SerialNumber == value) return;
                _serialNumber = value;
                FirePropertyChanged("SerialNumber");
            }
        }

        public bool IsBusy
        {
            get { return _IsBusy; }
            internal set
            {
                _IsBusy = value;
                FirePropertyChanged("IsBusy");
            }
        }

        public Visibility CustomerVisibility
        {
            get { return _CustomerVisibility; }
            internal set
            {
                _CustomerVisibility = value;
                FirePropertyChanged("CustomerVisibility");
            }
        }

        public InventoryDTO Inventory
        {
            get { return _inventory; }
            internal set
            {
                _inventory = value;
                FirePropertyChanged("Inventory");
            }
        }

        public long RecordCount { get; set; }

        //Buat binding ke child form waktu mau edit
        public PreSalesOrderDTO PreSalesOrder
        {
            get { return _PreSalesOrder; }
            private set
            {
                if (PreSalesOrder == value) return;
                _PreSalesOrder = value;
                FirePropertyChanged("PreSalesOrder");
            }
        }

        public string Expression
        {
            get { return _Expression; }
            set
            {
                if (Expression == value) return;
                _Expression = value;
                FirePropertyChanged("Expression");
            }
        }

        public bool IsEnabled
        {
            get { return _IsEnabled; }
            internal set
            {
                _IsEnabled = value;
                FirePropertyChanged("IsEnabled");
            }
        }

        public ICommand OnPageChanged { get; set; }
        public ICommand Save { get; set; }
        public ICommand New { get; set; }
        public ICommand Edit { get; set; }
        public ICommand Unload { get; set; }
        public ICommand SearchCommand { get; set; }
        public ICommand SearchResultCommand { get; set; }
        public ICommand CancelCommand { get; set; }


        public ICommand GetCustomerCommand { get; set; }


        public List<string> Errors
        {
            get { return _errors; }
            private set
            {
                if (Errors == value) return;
                _errors = value;
                FirePropertyChanged("Errors");
            }
        }

        public Visibility MessageVisibility
        {
            get { return _messageVisibility; }
            private set
            {
                if (MessageVisibility == value) return;
                _messageVisibility = value;
                FirePropertyChanged("MessageVisibility");
            }
        }


        public string this[string columnName]
        {
            get
            {
                if (validationHandler.BrokenRuleExists(columnName))
                {
                    return validationHandler[columnName];
                }
                return null;
            }
        }

        public ICommand LoadInvoiceCommand { get; set; }
        public ICommand SendCommand { get; set; }

        private void PrepareEdit()
        {
            PreSalesOrder = (PreSalesOrderDTO) Navigation.Args;
            GetPreSalesOrder(PreSalesOrder);
            CekTransaksi();
        }


        private void GetPreSalesOrder(PreSalesOrderDTO preSalesOrder)
        {
            IsBusy = true;
            client.GetPreSalesOrderCompleted += client_GetPreSalesOrderCompleted;
            client.GetPreSalesOrderAsync(preSalesOrder.PSNo);
        }

        private void client_GetPreSalesOrderCompleted(object sender, GetPreSalesOrderCompletedEventArgs e)
        {
            client.GetPreSalesOrderCompleted -= client_GetPreSalesOrderCompleted;
            PreSalesOrder = e.Result;
            if (PreSalesOrder.Status == Status.Void || PreSalesOrder.Status == Status.Close) IsEnabled = false;
            if (PreSalesOrder.PreSalesOrderDetails == null)
                PreSalesOrder.PreSalesOrderDetails = new ObservableCollection<PreSalesOrderDetailDTO>();
            else if (PreSalesOrder.PreSalesOrderDetails.Count == 0)
                PreSalesOrder.PreSalesOrderDetails.Add(new PreSalesOrderDetailDTO());
            IsBusy = false;
            GetWarehouseList();
        }

        public bool CanGetCustomer(Object param)
        {
            return true;
        }

        public void GetCustomer(Object param)
        {
            CustomerClient.GetCustomerListCompleted += CustomerClient_GetCustomerListCompleted;
            CustomerClient.GetCustomerListAsync(param.ToString());
        }

        private void CustomerClient_GetCustomerListCompleted(object sender, GetCustomerListCompletedEventArgs e)
        {
            CustomerClient.GetCustomerListCompleted -= CustomerClient_GetCustomerListCompleted;
            Customers = e.Result;
            CustomerVisibility = Visibility.Visible;
            EventAggregator.PublishMessage("CustomerSelect", string.Empty);
        }


        public void Complete(Object param)
        {
            OnSearchCompleted(param);
        }

        private void PreSalesOrder_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (((PagedCollectionView) sender).SortDescriptions.Count > 0)
            {
                if (((PagedCollectionView) sender).SortDescriptions[0].PropertyName.ToLower() == "no") return;

                PropertySort = ((PagedCollectionView) sender).SortDescriptions[0].PropertyName;
                if (string.IsNullOrEmpty(OrderType))
                {
                    OrderType = "ASC";
                }
                else
                {
                    OrderType = OrderType == "ASC" ? OrderType = "DESC" : OrderType = "ASC";
                }
                GetList(1, PropertySort);
            }
        }


        public void SavePreSalesOrder(Object preSalesOrder)
        {
            //PreSalesOrder = (PreSalesOrderDTO) preSalesOrder;
            if (PreSalesOrder.PreSalesOrderDetails.Count == 1)
            {
                //Bila tidak ada yang dipilih di detail maka details harus dihapus
                if (PreSalesOrder.PreSalesOrderDetails[0].Inventory == null)
                    PreSalesOrder.PreSalesOrderDetails.Clear();
            }
            Validate();
            if (Errors.Count > 0) return;
            PreSalesOrder.created_by = GlobalVar.User.UserID;
            PreSalesOrder.modified_by = GlobalVar.User.UserID;
            client.SaveCompleted += client_SaveCompleted;
            IsBusy = true;
            client.SaveAsync(PreSalesOrder, mode);
        }

        private void client_SaveCompleted(object sender, SaveCompletedEventArgs e)
        {
            if (e.Error != null) Validate(e.Error.ToString());
            client.SaveCompleted -= client_SaveCompleted;
            mode = (Mode) e.UserState;
            if (e.Result)
            {
                IsBusy = false;
                ClearTransaksi(mode);
                mode = Mode.Idle;
                Navigation.MyNavigation.Navigate(new Uri("/PreSalesOrder/Index", UriKind.Relative));
            }
            else
            {
                IsBusy = false;
                MessageBox.Show("Simpan Gagal, Periksa data Anda!");
            }
        }


        public void GetList(int? page, string sortProp)
        {
            IsBusy = true;
            client.GetListCompleted += client_GetListCompleted;
            client.GetListAsync(page ?? 1, sortProp, OrderType);
        }

        private void client_GetListCompleted(object sender, GetListCompletedEventArgs e)
        {
            RecordCount = e.recordCount;
            if (PageSources == null) CreatePageNumber();
            client.GetListCompleted -= client_GetListCompleted;
            PreSalesOrders = new PagedCollectionView(e.Result);
            IsBusy = false;
            Complete(this);
        }


        private void NewPreSalesOrder(Object param)
        {
            mode = Mode.Add;
            Navigation.MyNavigation = (NavigationService) param;
            Navigation.MyNavigation.Navigate(new Uri("/PreSalesOrder/frmAdd", UriKind.Relative));
        }


        private void SearchPreSalesOrder(Object param)
        {
            mode = Mode.Search;
            frmSearch = new Search();
            frmSearch.Show();
        }


        private void SearchResult(Object param)
        {
            criteria = new Dictionary<string, object>();

            foreach (PropertyInfo prop in PreSalesOrder.GetType().GetProperties())
            {
                if (prop.PropertyType == typeof (Decimal))
                {
                    if ((Decimal) prop.GetValue(PreSalesOrder, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Int32))
                {
                    if ((Int32) prop.GetValue(PreSalesOrder, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Int64))
                {
                    if ((Int64) prop.GetValue(PreSalesOrder, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Double))
                {
                    if ((Double) prop.GetValue(PreSalesOrder, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (String))
                {
                    if (String.IsNullOrEmpty((String) prop.GetValue(PreSalesOrder, null))) continue;
                }
                if (prop.PropertyType == typeof (DateTime))
                {
                    if (prop.GetValue(PreSalesOrder, null).ToString().Contains("0001")) continue;
                }
                if (prop.GetValue(PreSalesOrder, null) == null) continue;
                if (prop.PropertyType.Name == "No") continue;

                if (prop.PropertyType.Name.ToLower().Contains("dto"))
                {
                    foreach (PropertyInfo propertyInfo in prop.GetValue(PreSalesOrder, null).GetType().GetProperties()
                        )
                    {
                        if (propertyInfo.Name.ToLower().Contains("id") || propertyInfo.Name.ToLower().Contains("kode") ||
                            propertyInfo.Name.ToLower().Contains("serial") ||
                            propertyInfo.Name.ToLower().Contains("code"))
                        {
                            criteria.Add(prop.Name, propertyInfo.GetValue(prop.GetValue(PreSalesOrder, null), null));
                            break;
                        }
                    }
                }
                else
                {
                    criteria.Add(prop.Name, prop.GetValue(PreSalesOrder, null));
                }
            }

            expression = string.Empty;
            if (frmSearch.rblOr.IsChecked ?? false) expression = "OR";
            else expression = "AND";
            PreSalesOrderSearch(criteria, expression,1);
        }

        private void PreSalesOrderSearch(Dictionary<String, Object> criteria, string expression,int page)
        {
            if (criteria.ContainsKey("Status")) criteria.Remove("Status");
            frmSearch.DialogResult = true;
            IsBusy = true;
            Complete(this);
            client.GetListByCriteriaCompleted += client_GetListByCriteriaCompleted;
            client.GetListByCriteriaAsync(criteria, expression, page);
        }

        private void client_GetListByCriteriaCompleted(object sender, GetListByCriteriaCompletedEventArgs e)
        {
            client.GetListByCriteriaCompleted -= client_GetListByCriteriaCompleted;
            PreSalesOrders = new PagedCollectionView(e.Result);
            if (RecordCount != e.recordCount)
            {
                RecordCount = e.recordCount;
                CreatePageNumber();
            }
            IsBusy = false;
        }


        private void CreatePageNumber()
        {
            Pages = new ObservableCollection<int>();
            for (int i = 0; i < RecordCount; i++)
            {
                Pages.Add(i);
            }
            PageSources = new PagedCollectionView(Pages);
        }


        private void PageIndexChanged(Object pageIndex)
        {
            //Jika Pertama kali jangan di Getlagi
            PreSalesOrder = null;
            if (PreSalesOrders != null && CurrentPage != (int) pageIndex)
            {
                CurrentPage = (int) pageIndex;

                if (mode == Mode.Search)
                    PreSalesOrderSearch(criteria, expression, (int)pageIndex + 1);
                else if (String.IsNullOrEmpty(PropertySort))
                    GetList((int) pageIndex + 1, null);
                else GetList((int) pageIndex + 1, PropertySort);
            }
        }


        public bool CanPageIndexChanged(Object param)
        {
            return true;
        }


        public bool CanSave(Object param)
        {
            return true;
        }


        public bool CanNew(Object param)
        {
            return true;
        }

        public bool CanEdit(Object param)
        {
            return true;
        }


        public bool CanUnload(Object param)
        {
            return true;
        }


        public bool CanSearch(Object param)
        {
            return true;
        }

        public bool CanSearchResult(Object param)
        {
            return true;
        }

        public bool CanCancelCommand(Object param)
        {
            return true;
        }


        public void Release(Object param)
        {
            param = null;
            PreSalesOrder = null;
            OrderType = null;
            PropertySort = null;
            mode = Mode.Idle;
        }


        public void Refresh()
        {
            if (PreSalesOrders == null)
                GetList(1, null);
            else
                Complete(this);
        }


        public void Validate(string error = null)
        {
            Errors = new List<string>();
            //if (string.IsNullOrEmpty(PreSalesOrder.PSNo))
            //    Errors.Add("Nomor SR tidak boleh kosong");
            if (PreSalesOrder.PreSalesOrderDetails.Count < 1)
                Errors.Add("PreSalesOrder Detail harus diisi!");
            if (!string.IsNullOrEmpty(error))
                Errors.Add(error);

            //validasi Detail
            //Hapus baris terakhir

            var count = PreSalesOrder.PreSalesOrderDetails.Count - 1;
            for (int i = 0; i <= count - 1; i++)
            {
                if (PreSalesOrder.PreSalesOrderDetails[i].Inventory == null || 
                    string.IsNullOrEmpty(PreSalesOrder.PreSalesOrderDetails[i].Inventory.SerialNumber))
                    PreSalesOrder.PreSalesOrderDetails.RemoveAt(i);
            }
          


            if (Errors.Count > 0)
            {
                MessageVisibility = Visibility.Visible;
            }
            else
            {
                MessageVisibility = Visibility.Collapsed;
            }
        }

        public void Cancel(Object param)
        {
            MessageBoxResult res = MessageBox.Show("Are You Sure Want to Cancel ?", "Confirmation",
                                                   MessageBoxButton.OKCancel);
            if (res == MessageBoxResult.OK)
            {
                if (!IsUsed) ClearTransaksi(mode);
                mode = Mode.Idle;
                Navigation.MyNavigation.GoBack();
            }
        }

        private void GetLastNoPreSalesOrder()
        {
            client = new PreSalesOrderServicesClient();
            client.GetLastSRNoCompleted +=
                client_GetLastNoPreSalesOrderCompleted;
            client.GetLastSRNoAsync();
        }

        private void client_GetLastNoPreSalesOrderCompleted(object sender, GetLastSRNoCompletedEventArgs e)
        {
            client.GetLastSRNoCompleted -=
                client_GetLastNoPreSalesOrderCompleted;
            string res = e.Result;
            string formatSO = "0000";
            string kodeSO;
            if (e.Result.Length <= 4)
            {
                res = formatSO;
                kodeSO = e.Result;
            }
            else
            {
                res = e.Result.Split(new[] {"/"}, StringSplitOptions.RemoveEmptyEntries)[2];
                kodeSO = e.Result.Split(new[] {"/"}, StringSplitOptions.RemoveEmptyEntries)[0];
            }

            string soNum = formatSO.Substring(0, formatSO.Length - (int.Parse(res) + 1).ToString().Length) +
                           (int.Parse(res) + 1);
            PreSalesOrder.PSNo = kodeSO + "/" + DateTime.Now.Year + "/" + soNum;
        }
      

        public bool CanLoadInvoiceCommand(Object param)
        {
            return true;
        }

    

        public bool CanSendCommand(Object param)
        {
            return true;
        }

        public void SendEmail(Object param)
        {
            ChooseDestination chooseDestination = new ChooseDestination();
            chooseDestination.Show();
            EventAggregator.RegisterMessage("SendDestination", (x) =>
            {
                IsBusy = true;
                client.SendEmailCompleted += client_SendEmailCompleted;
                client.SendEmailAsync(param as PreSalesOrderDTO, (x as WarehouseDTO).EmailFolder);
            });

        }

        private void client_SendEmailCompleted(object sender, PreSalesOrderServices.SendEmailCompletedEventArgs e)
        {
            IsBusy = false;
            client.SendEmailCompleted -= client_SendEmailCompleted;
            if (e.Result) MessageBox.Show("Pengiriman Selesai");
        }


        public void GetItemList(Object param)
        {
            ItemClient.GetItemByNameCompleted += ItemClient_GetItemByNameCompleted;
            ItemClient.GetItemByNameAsync(param.ToString());
        }

        private void ItemClient_GetItemByNameCompleted(object sender, GetItemByNameCompletedEventArgs e)
        {
            ItemClient.GetItemByNameCompleted -= ItemClient_GetItemByNameCompleted;
            Items = e.Result;
        }

        public void GetSubGrouplist(Object param)
        {
            SubgroupClient.GetSubGroupListByNameCompleted += SubgroupClient_GetSubGroupListByNameCompleted;
            SubgroupClient.GetSubGroupListByNameAsync(param.ToString());
        }

        private void SubgroupClient_GetSubGroupListByNameCompleted(object sender,
                                                                   GetSubGroupListByNameCompletedEventArgs e)
        {
            SubgroupClient.GetSubGroupListByNameCompleted -= SubgroupClient_GetSubGroupListByNameCompleted;
            Subgroups = e.Result;
        }


        public void GetWarehouseList()
        {
            WarehouseClient.GetAllWarehouseCompleted += WarehouseClient_GetAllWarehouseCompleted;
            WarehouseClient.GetAllWarehouseAsync();
        }

        private void WarehouseClient_GetAllWarehouseCompleted(object sender, GetAllWarehouseCompletedEventArgs e)
        {
            WarehouseClient.GetAllWarehouseCompleted -= WarehouseClient_GetAllWarehouseCompleted;
            Warehouses = e.Result;
            if (mode == Mode.Edit)
            {
                if (PreSalesOrder.Warehouse != null)
                    PreSalesOrder.Warehouse =
                        Warehouses.FirstOrDefault(x => x.KodeWarehouse == PreSalesOrder.Warehouse.KodeWarehouse);
            }
        }

        

        public void GetPalletList(Object param)
        {
            PalletClient.GetPalletByWarehouseCompleted += PalletClient_GetPalletByWarehouseCompleted;
            PalletClient.GetPalletByWarehouseAsync(param as WarehouseDTO);
        }

        private void PalletClient_GetPalletByWarehouseCompleted(object sender, GetPalletByWarehouseCompletedEventArgs e)
        {
            PalletClient.GetPalletByWarehouseCompleted -= PalletClient_GetPalletByWarehouseCompleted;
            Pallets = e.Result;
        }

        public void CekTransaksi()
        {
            ApplicationService.IsTransactionUsedCompleted += ApplicationService_IsTransactionUsedCompleted;
            if (string.IsNullOrEmpty(PreSalesOrder.PSNo))
            {
                ApplicationService.IsTransactionUsedAsync(PreSalesOrder.ToString(), GlobalVar.User, mode);
                GlobalVar.CurrentTransaction = PreSalesOrder.ToString();
            }
            else
            {
                ApplicationService.IsTransactionUsedAsync(PreSalesOrder.PSNo, GlobalVar.User, mode);
                GlobalVar.CurrentTransaction = PreSalesOrder.PSNo;
            }
        }

        private void ApplicationService_IsTransactionUsedCompleted(object sender, IsTransactionUsedCompletedEventArgs e)
        {
            ApplicationService.IsTransactionUsedCompleted -= ApplicationService_IsTransactionUsedCompleted;
            IsUsed = e.Result;
            mode = (Mode) e.UserState;
            if (IsUsed)
            {
                MessageBox.Show("Transaksi sedang digunakan!");
                if (mode == Mode.Add) //If Add Mode
                {
                    mode = Mode.Idle;
                    Navigation.MyNavigation.Navigate(new Uri("/PreSalesOrder/Index", UriKind.Relative));
                }
                else //Edit Mode just view Only
                {
                    IsEnabled = false;
                }
            }
        }

        private void ClearTransaksi(Mode mode)
        {
            ApplicationService.ClearTransactionCompleted += ApplicationService_ClearTransactionCompleted;
            if (mode == Mode.Add)
                ApplicationService.ClearTransactionAsync(PreSalesOrder.ToString(), GlobalVar.User);
            else
                ApplicationService.ClearTransactionAsync(PreSalesOrder.PSNo, GlobalVar.User);
        }

        private void ApplicationService_ClearTransactionCompleted(object sender, AsyncCompletedEventArgs e)
        {
            ApplicationService.ClearTransactionCompleted -= ApplicationService_ClearTransactionCompleted;
        }


        public void LoadDetailFromFile(Object param)
        {
            ImportHelper importHelper = new ImportHelper();
            IEnumerable<List<dynamic>> sourcesOld;
            importHelper.BrowseExcelFile(out sourcesOld);
            var sources = importHelper.LoadExcellFile(importHelper.listSheetNames.FirstOrDefault());
           

            ObservableCollection<InventoryDTO> inventoryDtos = new ObservableCollection<InventoryDTO>();
            if (sourcesOld == null || sourcesOld.Count() == 0)
            {
                if (sources != null)
                {
                    foreach (dynamic data in sources)
                    {
                        string noLog = data.A;
                        if (string.IsNullOrEmpty(noLog)) continue;
                        inventoryDtos.Add(new InventoryDTO() { SerialNumber = noLog });
                    }
                }

            }
            else
            {
                int i = 0;

                foreach (var data in sourcesOld)
                {
                    if (i > 0)
                    {
                        string noLog = data[0];
                        if (string.IsNullOrEmpty(noLog)) continue;
                        inventoryDtos.Add(new InventoryDTO() { SerialNumber = noLog });
                    }
                    i++;
                }
            }


            if (inventoryDtos.Count > 0)
                GetInventoryList(inventoryDtos);
        }

        public void GetInventoryList(ObservableCollection<InventoryDTO> inventoryDtos)
        {
        
            if (PreSalesOrder.Warehouse == null)
            {
                MessageBox.Show("Warehouse dipilih dulu!");
                return;
            }
            InventoryClient.GetInventoryListbyWarehouseCompleted += new EventHandler<GetInventoryListbyWarehouseCompletedEventArgs>(InventoryClient_GetInventoryListbyWarehouseCompleted);
            InventoryClient.GetInventoryListbyWarehouseAsync(inventoryDtos,PreSalesOrder.Warehouse.KodeWarehouse);
            IsBusy = true;
        }

        void InventoryClient_GetInventoryListbyWarehouseCompleted(object sender, GetInventoryListbyWarehouseCompletedEventArgs e)
        {
            InventoryClient.GetInventoryListbyWarehouseCompleted -= new EventHandler<GetInventoryListbyWarehouseCompletedEventArgs>(InventoryClient_GetInventoryListbyWarehouseCompleted);

            foreach (var InventoryTemp in e.Result)
            {
                var PreSalesOrderDetail = new PreSalesOrderDetailDTO();
                if (PreSalesOrderDetail != null && InventoryTemp != null)
                {
                    PreSalesOrderDetail.Inventory = InventoryTemp;
                    PreSalesOrderDetail.Panjang = InventoryTemp.Panjang;
                    PreSalesOrderDetail.Lebar = InventoryTemp.Lebar;
                    PreSalesOrderDetail.Tinggi = InventoryTemp.Warehouses.FirstOrDefault().Sheet;
                    PreSalesOrderDetail.QtyUnit = InventoryTemp.Warehouses.FirstOrDefault().Qty;
                    PreSalesOrder.PreSalesOrderDetails.Add(PreSalesOrderDetail);
                }

            }

            IsBusy = false;
        }


    }


    public class PreSalesOrderWrapViewModel : ViewModelBase
    {
        private readonly InventoryServiceClient InventoryClient;
        private readonly PalletServicesClient PalletClient;
        private readonly WarehouseServicesClient WarehouseClient;
        private readonly PreSalesOrderServicesClient client;

        private ObservableCollection<InventoryDTO> _Inventorys;
        private ObservableCollection<PalletDTO> _Pallets;
        private PreSalesOrderDetailDTO _PreSalesOrderDetail;
        private ObservableCollection<WarehouseDTO> _Warehouses;


        public PreSalesOrderWrapViewModel()
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                client = new PreSalesOrderServicesClient();
                InventoryClient = new InventoryServiceClient();
                PalletClient = new PalletServicesClient();
                WarehouseClient = new WarehouseServicesClient();

                EditCommand = new DelegateCommand(Edit, CanEditCommand);
                DeleteCommand = new DelegateCommand(Delete, CanDeleteCommand);
                AddDetailCommand = new DelegateCommand(AddPreSalesOrderDetail, CanAddDetailCommand);
                DeleteDetailCommand = new DelegateCommand(DeletePreSalesOrderDetail, CanDeleteDetailCommand);
                GetInventoryCommand = new DelegateCommand(GetInventory, CanGetInventoryCommand);
                GetTotalDetailCommand = new DelegateCommand(GetTotalDetail, CanGetTotalDetailCommand);
                GetQtyUnitCommand = new DelegateCommand(GetQtyUnit, CanGetQtyUnit);

                if (PreSalesOrderViewModel.mode == Mode.Add || PreSalesOrderViewModel.mode == Mode.Edit)
                {
                }
            }
        }

        public PreSalesOrderViewModel PreSalesOrderViewModel { get; set; }

        public ICommand EditCommand { get; set; }
        public ICommand DeleteCommand { get; set; }
        public ICommand AddDetailCommand { get; set; }
        public ICommand DeleteDetailCommand { get; set; }

        public ObservableCollection<InventoryDTO> Inventorys
        {
            get { return _Inventorys; }
            private set
            {
                if (Inventorys == value) return;
                _Inventorys = value;
                FirePropertyChanged("Inventorys");
            }
        }

        public ObservableCollection<PalletDTO> Pallets
        {
            get { return _Pallets; }
            private set
            {
                if (Pallets == value) return;
                _Pallets = value;
                FirePropertyChanged("Pallets");
            }
        }

        public ObservableCollection<WarehouseDTO> Warehouses
        {
            get { return _Warehouses; }
            private set
            {
                if (Warehouses == value) return;
                _Warehouses = value;
                FirePropertyChanged("Warehouses");
            }
        }


        public PreSalesOrderDetailDTO PreSalesOrderDetail
        {
            get { return _PreSalesOrderDetail; }
            private set
            {
                if (PreSalesOrderDetail == value) return;
                _PreSalesOrderDetail = value;
                FirePropertyChanged("PreSalesOrderDetail");
            }
        }

        public ICommand GetInventoryCommand { get; set; }
        public ICommand GetQtyUnitCommand { get; set; }
        public ICommand GetTotalDetailCommand { get; set; }

        public bool CanEditCommand(Object param)
        {
            return true;
        }

        public bool CanDeleteCommand(Object param)
        {
            return true;
        }

        public bool CanAddDetailCommand(Object param)
        {
            return true;
        }

        public bool CanDeleteDetailCommand(Object param)
        {
            return true;
        }

        public void Edit(Object param)
        {
            PreSalesOrderViewModel.mode = Mode.Edit;
            Navigation.MyNavigation.Navigate(new Uri("/PreSalesOrder/frmAdd", UriKind.Relative));
            Navigation.Args = param;
        }

        public void Delete(Object param)
        {
            DeleteConfirmation deleteConfirmation = new DeleteConfirmation();
            deleteConfirmation.Show();
            EventAggregator.RegisterMessage("ApprovalSucceeded", (x) =>
            {
                deleteConfirmation.Close();
                client.DeleteCompleted += client_DeleteCompleted;
                client.DeleteAsync((PreSalesOrderDTO)param);
            });
            
        }

        private void client_DeleteCompleted(object sender, AsyncCompletedEventArgs e)
        {
            client.DeleteCompleted -= client_DeleteCompleted;
            MessageBox.Show("Delete Success!");
            PreSalesOrderViewModel.mode = Mode.Idle;
            var VM = new PreSalesOrderViewModel();
        }


        public void GetInventoryList()
        {
            InventoryClient.GetInventoryByCriteriaCompleted +=
                InventoryClient_GetListByCriteriaCompleted;
            InventoryClient.GetInventoryByCriteriaAsync(new Dictionary<string, object>(), null, 1);
        }

        private void InventoryClient_GetListByCriteriaCompleted(object sender,
                                                                GetInventoryByCriteriaCompletedEventArgs e)
        {
            Inventorys = e.Result;
            if (PreSalesOrderViewModel.PreSalesOrder != null)
            {
                foreach (
                    PreSalesOrderDetailDTO PreSalesOrderDetail in
                        PreSalesOrderViewModel.PreSalesOrder.PreSalesOrderDetails)
                {
                    if (PreSalesOrderDetail.Inventory == null) continue;
                    PreSalesOrderDetail.Inventory =
                        Inventorys.FirstOrDefault(s => s.SerialNumber == PreSalesOrderDetail.Inventory.SerialNumber);
                }
            }
        }

        public void GetInventory2(String SerialNumber)
        {
            if (PreSalesOrderViewModel.PreSalesOrder.Warehouse == null)
            {
                MessageBox.Show("Warehouse dipilih dulu!");
                return;
            }
            InventoryClient.GetInventoryCompleted +=
                InventoryClient_GetInventoryCompleted2;
            InventoryClient.GetInventoryAsync(SerialNumber);
        }

        public void GetInventory(Object param)
        {
            if (PreSalesOrderViewModel.PreSalesOrder.Warehouse == null)
            {
                MessageBox.Show("Warehouse dipilih dulu!");
                return;
            }
            PreSalesOrderDetail = (PreSalesOrderDetailDTO) param;
            string SerialNumber = PreSalesOrderDetail.Inventory.SerialNumber;
            InventoryClient.GetInventoryCompleted +=
                InventoryClient_GetInventoryCompleted;
            InventoryClient.GetInventoryAsync(SerialNumber,PreSalesOrderDetail);
        }

        private bool ValidateSerialNumber(string SerialNumber)
        {
            if (PreSalesOrderViewModel.PreSalesOrder.PreSalesOrderDetails.Count > 0 &&
                PreSalesOrderViewModel.PreSalesOrder.PreSalesOrderDetails.Any(
                    x => x.Inventory.SerialNumber == SerialNumber && x.Inventory.Item != null))
            {
                MessageBox.Show("No.Log " + SerialNumber + " tidak valid!, Silahkan pilih yang lain!");
                return false;
            }
            return true;
        }

        private void InventoryClient_GetInventoryCompleted(object sender, GetInventoryCompletedEventArgs e)
        {
            InventoryClient.GetInventoryCompleted -=
                InventoryClient_GetInventoryCompleted;

            InventoryDTO InventoryTemp = e.Result;
            if (null != InventoryTemp && ! string.IsNullOrEmpty(InventoryTemp.SerialNumber))
            {
                if (ValidateSerialNumber(InventoryTemp.SerialNumber) == false) return;
                PreSalesOrderDetail = e.UserState as PreSalesOrderDetailDTO;
                if (!InventoryTemp.Warehouses.Any(x => x.KodeWarehouse == PreSalesOrderViewModel.PreSalesOrder.Warehouse.KodeWarehouse))
                {
                    MessageBox.Show("Tidak Ada SerialNumber " + InventoryTemp.SerialNumber + " di " +
                                    PreSalesOrderViewModel.PreSalesOrder.Warehouse.KodeWarehouse);
                    return;
                }
                if (PreSalesOrderDetail != null)
                {
                    PreSalesOrderDetail.Inventory = InventoryTemp;
                    PreSalesOrderDetail.Panjang = InventoryTemp.Panjang;
                    PreSalesOrderDetail.Lebar = InventoryTemp.Lebar;
                    PreSalesOrderDetail.Tinggi = InventoryTemp.Warehouses.FirstOrDefault(x=>x.KodeWarehouse == PreSalesOrderViewModel.PreSalesOrder.Warehouse.KodeWarehouse).Sheet;
                    PreSalesOrderDetail.QtyUnit = InventoryTemp.Warehouses.FirstOrDefault(x => x.KodeWarehouse == PreSalesOrderViewModel.PreSalesOrder.Warehouse.KodeWarehouse).Qty;
                }
            }else
            {
                MessageBox.Show("Barang tidak ditemukan, coba entry secara manual");
            }
        }

        private void InventoryClient_GetInventoryCompleted2(object sender, GetInventoryCompletedEventArgs e)
        {
            InventoryClient.GetInventoryCompleted -=
                InventoryClient_GetInventoryCompleted2;

            InventoryDTO InventoryTemp = e.Result;

            if (string.IsNullOrEmpty(InventoryTemp.SerialNumber) || !InventoryTemp.Warehouses.Any(x => x.KodeWarehouse == PreSalesOrderViewModel.PreSalesOrder.Warehouse.KodeWarehouse))
            {
                MessageBox.Show("Tidak Ada SerialNumber " + InventoryTemp.SerialNumber + " di " +
                                PreSalesOrderViewModel.PreSalesOrder.Warehouse.KodeWarehouse);
                return;
            }


            if (null != InventoryTemp && !string.IsNullOrEmpty(InventoryTemp.SerialNumber))
            {
                if (ValidateSerialNumber(InventoryTemp.SerialNumber) == false) return;
                PreSalesOrderDetail = new PreSalesOrderDetailDTO();
                PreSalesOrderDetail.Inventory = InventoryTemp;
                PreSalesOrderDetail.Panjang = InventoryTemp.Panjang;
                PreSalesOrderDetail.Lebar = InventoryTemp.Lebar;
                PreSalesOrderDetail.Tinggi = InventoryTemp.Warehouses.FirstOrDefault(x => x.KodeWarehouse == PreSalesOrderViewModel.PreSalesOrder.Warehouse.KodeWarehouse).Sheet;
                PreSalesOrderDetail.QtyUnit = InventoryTemp.Warehouses.FirstOrDefault(x => x.KodeWarehouse == PreSalesOrderViewModel.PreSalesOrder.Warehouse.KodeWarehouse).Qty;
                PreSalesOrderViewModel.PreSalesOrder.PreSalesOrderDetails.Add(PreSalesOrderDetail);
            }
            else
            {
                MessageBox.Show("Barang tidak ditemukan, coba entry secara manual");
            }
        }

        public void AddPreSalesOrderDetail(Object param)
        {
            PreSalesOrderDetail = new PreSalesOrderDetailDTO();
            PreSalesOrderViewModel.PreSalesOrder.PreSalesOrderDetails.Add(PreSalesOrderDetail);
        }

        public void DeletePreSalesOrderDetail(Object param)
        {
            if (param == null && PreSalesOrderViewModel.PreSalesOrder.PreSalesOrderDetails.Count > 1)
            {
                PreSalesOrderViewModel.PreSalesOrder.PreSalesOrderDetails.RemoveAt(
                    PreSalesOrderViewModel.PreSalesOrder.PreSalesOrderDetails.Count - 1);
                GetTotalDetail(PreSalesOrderDetail);
                return;
            }
            if (PreSalesOrderViewModel.PreSalesOrder.PreSalesOrderDetails.Count > 1)
            {
                var PreSalesOrderDetail = (PreSalesOrderDetailDTO)param;
                PreSalesOrderViewModel.PreSalesOrder.PreSalesOrderDetails.Remove(PreSalesOrderDetail);
                GetTotalDetail(PreSalesOrderDetail);
            }
        }

        public bool CanGetInventoryCommand(Object param)
        {
            return true;
        }

        public bool CanGetQtyUnit(Object param)
        {
            return true;
        }

        public void GetQtyUnit(Object param)
        {
            PreSalesOrderDetail = param as PreSalesOrderDetailDTO;
            if (PreSalesOrderDetail != null)
                if (PreSalesOrderDetail.Inventory != null)
                    if (PreSalesOrderDetail.Inventory.SatuanUnit != null)
                    {
                        PreSalesOrderDetail.QtyUnit = PreSalesOrderDetail.Inventory.QtyPack *
                                                       (PreSalesOrderDetail.Panjang *
                                                        PreSalesOrderDetail.Lebar *
                                                        PreSalesOrderDetail.Tinggi) /
                                                       PreSalesOrderDetail.Inventory.SatuanUnit.Pengali;

                        PreSalesOrderDetail.QtyUnit = PreSalesOrderDetail.Inventory.Item.IsRounded
                                                          ? PreSalesOrderDetail.QtyUnit.Round(2,
                                                                                              MidpointRounding.
                                                                                                  AwayFromZero)
                                                          : PreSalesOrderDetail.QtyUnit.Round(4,
                                                                                              MidpointRounding.
                                                                                                  AwayFromZero);
                    }
                       

           

        }


        public bool CanGetTotalDetailCommand(Object param)
        {
            return true;
        }

        public void GetTotalDetail(Object param)
        {
            PreSalesOrderDetail = (PreSalesOrderDetailDTO) param;
            PreSalesOrderDetail.TotalDetail = (PreSalesOrderDetail.Price) -
                                              ((PreSalesOrderDetail.Price)*PreSalesOrderDetail.Discount/100);
            PreSalesOrderViewModel.PreSalesOrder.Total =
                PreSalesOrderViewModel.PreSalesOrder.PreSalesOrderDetails.Sum(p => p.TotalDetail);
        }
    }
}